package com.zy.smarthome.service;

import com.zy.smarthome.common.util.DistributedLink;
import com.zy.smarthome.frame.util.FrameDataDeal;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author wjming
 */
@Service
@Slf4j
public class ThreadPoolService {

    /**
     * taskExecutor :指定使用那个线程池配置，不然会使用spring默认的线程池
     *
     * @param channel
     * @param frameAndChannel
     */
    @Async("taskExecutor")
    public void writeAndFlush(Channel channel, Map<String, Object> frameAndChannel) {
        try {
            String frame = (String) frameAndChannel.get("frame");
            String traceId = (String) frameAndChannel.get("traceId");
            DistributedLink.putTraceId(traceId);
            if (channel != null) {
                boolean writable = channel.isWritable();
                if (writable) {
                    channel.writeAndFlush(FrameDataDeal.dataToByte(frame));
                } else {
                    log.info("{} -> [数据不可达] [{}] -> [{}]", this.getClass().getName(), channel.id(), frame);
                }
                log.info("{} -> [下发数据] [{}] -> [{}]", this.getClass().getName(), channel.id(), frame);
            } else {
                log.error("{} -> [空通道] [{}] -> [{}]", this.getClass().getName(), channel.id(), frame);
            }
        } catch (Exception e) {
            log.error("数据下发异常:[{}]", e.getMessage());
        }
    }

}
